﻿using UnityEngine;
using System;
using UnityEditor;

namespace AirSimUnity
{
    public class AirSimServer : MonoBehaviour
    {
        private const string DRONE_MODE = "Multirotor";

        // Start is called before the first frame update
        void Start()
        {
            string simMode = AirSimSettings.GetSettings().SimMode;
            int basePortId = AirSimSettings.GetSettings().GetPortIDForVehicle(simMode == DRONE_MODE);

            Debug.Log(simMode + "," + basePortId);

            try
            {
                bool isServerStarted = PInvokeWrapper.StartServer(simMode, basePortId);
                if (isServerStarted == false)
                {
#if UNITY_EDITOR
                    EditorUtility.DisplayDialog("Problem in starting AirSim server!!!",
                        "Please check logs for more information." + simMode + "," + basePortId, "Exit");


                    EditorApplication.isPlaying = false;
#else
                Application.Quit();
#endif
                }
            }
            catch (Exception e)
            {
                Debug.Log(e.Message);
                PInvokeWrapper.StopServer();
                throw;
            }
        }

        protected void OnApplicationQuit()
        {
            PInvokeWrapper.StopServer();
        }
    }
}